﻿using Microsoft.EntityFrameworkCore;
using S.EliminationOrDath.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace S.EliminationOrDath.Infrastructure
{
    /// <summary>
    /// 仓储--通用方法
    /// </summary>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly EliminationDbContext db;

        public BaseRepository(EliminationDbContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="t">实体类</param>
        /// <returns></returns>
        public async Task<bool> Add(T t)
        {
            await db.Set<T>().AddAsync(t);
            return await db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public async Task<bool> AddRange(List<T> ts)
        {
            await db.Set<T>().AddRangeAsync(ts);
            return await db.SaveChangesAsync() > 0;
        }

        //public async Task<bool> BacthDelete(List<int> ids)
        //{
        //    var result = await db.Set<T>().Where(a => ids.Contains(a.));
        //}

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Delete(int id)
        {
            T? obj = await db.Set<T>().FindAsync(id);
            if (obj == null)
            {
                return false;
            }
            db.Set<T>().Remove(obj);
            return await db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public async Task<bool> DeleteRange(List<T> ts)
        {
            db.Set<T>().RemoveRange(ts);
            return await db.SaveChangesAsync() > 0;
        }

        /// <summary>
        /// 查询方法
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<T>> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<bool> Update(T t)
        {
            await Task.Run(() => db.Set<T>().Update(t));
            return await db.SaveChangesAsync() > 0;
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public async Task<bool> UpdateRange(List<T> ts)
        {
            db.Set<T>().UpdateRange(ts);
            return await db.SaveChangesAsync() > 0;
        }
    }
}
